package com.example.leaderapplication.View.Fragment;

import android.text.Html;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;
import androidx.recyclerview.widget.StaggeredGridLayoutManager;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;
import androidx.viewpager.widget.ViewPager;

import com.example.leaderapplication.Adapter.HomeRecyclerViewAdapter;
import com.example.leaderapplication.Adapter.ImageAdapter;
import com.example.leaderapplication.Adapter.ImageNetAdapter;
import com.example.leaderapplication.Adapter.RecyclerViewItemDecoration;
import com.example.leaderapplication.Base.BaseConfig;
import com.example.leaderapplication.Base.BaseFragment;
import com.example.leaderapplication.Bean.DataBean;
import com.example.leaderapplication.Bean.TabSelect;
import com.example.leaderapplication.Bean.findDocumentCatagoryAdvertisementListRequestBean;
import com.example.leaderapplication.Bean.findDocumentCatagoryAdvertisementListResultBean;
import com.example.leaderapplication.Bean.findDocumentCatagoryContentListResultBean;
import com.example.leaderapplication.Bean.loginByLeaderResultBean;
import com.example.leaderapplication.R;
import com.example.leaderapplication.RetrufitHelp.BaseSubscriber;
import com.example.leaderapplication.RetrufitHelp.ExceptionHandle;
import com.example.leaderapplication.RetrufitHelp.RetrofitClient;
import com.example.leaderapplication.Utils.ListDataSave;
import com.example.leaderapplication.Utils.LogUtil;
import com.example.leaderapplication.Utils.SPUtil;
import com.example.leaderapplication.Utils.ToastUtil;
import com.google.android.material.snackbar.Snackbar;
import com.google.gson.Gson;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.youth.banner.Banner;
import com.youth.banner.indicator.CircleIndicator;
import com.youth.banner.listener.OnPageChangeListener;
import com.youth.banner.util.BannerUtils;
import com.youth.banner.util.LogUtils;

import java.util.ArrayList;
import java.util.List;

import okhttp3.ResponseBody;

//说明：  下面展示的数据，由登入页面传递过来 要注意

public class HomePageFragment extends BaseFragment implements OnPageChangeListener {

    private static HomePageFragment homePageFragment;
    private static Banner banner;
    private RecyclerView mRecyclerView;
    private ListDataSave listDataSave;
    private List<loginByLeaderResultBean.DataBean.MenuListBean> dataList;
    private HomeRecyclerViewAdapter mAdapter;
    private static String baseUrl;
    private List<DataBean> mDatas;
    private ImageNetAdapter adapter;
    private RefreshLayout refreshLayout;
    private TextView homeAdvence;

    public static HomePageFragment getInstance(String Url) {
        if (homePageFragment == null) {
            homePageFragment = new HomePageFragment();
            baseUrl = Url;
        }
        return homePageFragment;
    }

    protected View rootView;

    @Override
    public View setView(LayoutInflater inflater) {
        if (rootView == null) {
            rootView = inflater.inflate(R.layout.fragment_home_page, null);
        }
        return rootView;
    }

    @Override
    public void initView() {
        if (dataList == null) {
            dataList = new ArrayList<>();
        }

        refreshLayout = (RefreshLayout) view.findViewById(R.id.srl_home_page_reflsh);
        homeAdvence = (TextView) view.findViewById(R.id.home_advence);

        // 条目的选择
        mRecyclerView = (RecyclerView) view.findViewById(R.id.rv_tab);
        // 两列
        int spanCount = 2;

        // StaggeredGridLayoutManager管理RecyclerView的布局。
        StaggeredGridLayoutManager mLayoutManager = new StaggeredGridLayoutManager(spanCount, StaggeredGridLayoutManager.VERTICAL);
        mRecyclerView.setLayoutManager(mLayoutManager);

        //为RecyclerView增加分割线，水平和垂直方向都有。增加分割线值比如为32。
        RecyclerViewItemDecoration decoration = new RecyclerViewItemDecoration(32);
        mRecyclerView.addItemDecoration(decoration);
        mAdapter = new HomeRecyclerViewAdapter(getContext(), dataList);
        mRecyclerView.setAdapter(mAdapter);

        //顶部图片
        if (mDatas == null) {
            mDatas = new ArrayList<>();
        }

        banner = (Banner) view.findViewById(R.id.banner);

        adapter = new ImageNetAdapter(mDatas);

        banner.setAdapter(adapter)//设置适配器
//              .setCurrentItem(3,false)
                .addBannerLifecycleObserver(this)//添加生命周期观察者
                .setBannerRound(BannerUtils.dp2px(20))//圆角
//              .addPageTransformer(new RotateYTransformer())//添加切换效果
                .setIndicator(new CircleIndicator(getActivity()))//设置指示器
                .setIndicatorSelectedColor(getActivity().getResources().getColor(R.color.color_blue))
                .addOnPageChangeListener(this)//添加切换监听
        ;//设置点击事件,传this也行
        refreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                // 这里做下拉刷新操作
                refreshlayout.finishRefresh(2000/*,false*/);//传入false表示刷新失败
            }
        });
        refreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(RefreshLayout refreshlayout) {
                // 这里做上拉刷新操作
                refreshlayout.finishLoadMore(2000/*,false*/);//传入false表示加载失败
            }
        });

        // 去请求 轮播图照片
        findDocumentCatagoryAdvertisementList();

        // 去请求公告
        findDocumentCatagoryContentList();
    }

    private void findDocumentCatagoryContentList() {
        RetrofitClient.getInstance(getContext(), baseUrl).findDocumentCatagoryContentList(new BaseSubscriber<findDocumentCatagoryContentListResultBean>(getContext()) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable e) {
                ToastUtil.showToast("获取公告失败");
            }

            @Override
            public void onNext(findDocumentCatagoryContentListResultBean findDocumentCatagoryContentListResultBean) {
//                homeAdvence.setText(findDocumentCatagoryContentListResultBean.getData().get(0).getDocumentCatagoryContent());
                homeAdvence.setText(Html.fromHtml(findDocumentCatagoryContentListResultBean.getData().get(0).getDocumentCatagoryContent()));
            }
        });
    }

    private void findDocumentCatagoryAdvertisementList() {
        findDocumentCatagoryAdvertisementListRequestBean findBean = new findDocumentCatagoryAdvertisementListRequestBean();
        findBean.setAdvertisementForPagePos(2);
        findBean.setAdvertisementType(2);
        RetrofitClient.getInstance(getContext(), baseUrl).findDocumentCatagoryAdvertisementList(findBean, new BaseSubscriber<findDocumentCatagoryAdvertisementListResultBean>(getContext()) {
            @Override
            public void onError(ExceptionHandle.ResponeThrowable e) {
                ToastUtil.showToast("获取轮播图失败");
            }

            @Override
            public void onNext(findDocumentCatagoryAdvertisementListResultBean responseBody) {

                // 获取轮播图成功,添加数据
                mDatas.clear();
                for (int i = 0; i < responseBody.getData().size(); i++) {
                    DataBean dataBean = new DataBean(responseBody.getData().get(i).getPicturePath(), "", 1);
                    mDatas.add(dataBean);
                }
                adapter.notifyDataSetChanged();

            }
        });
    }

    @Override
    public void initData() {
        // 获取 保存的数据 去显示条目
        listDataSave = new ListDataSave(getContext(), BaseConfig.SP_NAME);
        dataList.clear();
        List<loginByLeaderResultBean.DataBean.MenuListBean> list = listDataSave.getDataList(BaseConfig.HOME_ITEM, loginByLeaderResultBean.DataBean.MenuListBean.class);
        dataList.addAll(list);
        for (int i = 0; i < list.size(); i++) {
            if (list.get(i).getMeta().getTitle().equals("营销分析")) {
                SPUtil.put(getContext(), BaseConfig.ANALYSE_PATH, list.get(i).getPath());
            }
        }
        mAdapter.notifyDataSetChanged();
    }


    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

    }

    @Override
    public void onPageSelected(int position) {

    }

    @Override
    public void onPageScrollStateChanged(int state) {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        LogUtil.d("HomePageFragment + onDestroy");
        if (adapter != null) {
            adapter = null;
        }
        if (banner != null) {
            banner = null;

        }
    }
}
